package io.persimmon.springboot.aop;


import io.persimmon.core.exception.PersimmonException;
import io.persimmon.core.exception.PersimmonExceptionFactory;
import lombok.Data;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.util.Objects;

@Data
public class MethodAopInfo {

    private ProceedingJoinPoint proceedingJoinPoint;
    private Object target;
    private Method method;
    private Object[] args;
    private Object result;

    public MethodAopInfo(ProceedingJoinPoint proceedingJoinPoint) {
        this.proceedingJoinPoint = proceedingJoinPoint;

        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        this.target = proceedingJoinPoint.getTarget();
        this.method = signature.getMethod();
        this.args = proceedingJoinPoint.getArgs();
    }

    public MethodAopInfo(Object target, Method method, Object result) {
        this.target = target;
        this.method = method;
        this.result = result;
    }

    public Object invoke() throws PersimmonException {
        if (Objects.isNull(result)) {
            try {
                this.result = this.proceedingJoinPoint.proceed();
            } catch (Throwable e) {
                throw PersimmonExceptionFactory.create(e);
            }
        }
        return result;
    }

    public Object invoke(Object[] var1) {
        if (Objects.isNull(result)) {
            try {
                this.result = this.proceedingJoinPoint.proceed(var1);
            } catch (Throwable e) {
                throw PersimmonExceptionFactory.create(e);
            }
        }
        return result;
    }

    public String getAopMethodName() {
        return target.getClass().getName() + "#" + method.getName();
    }
}
